package servlets;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jpa.entities.Bestelling;
import jpa.entities.BestellingPK;
import jpa.entities.Product;
import jpa.interfaces.ProductBeanInterface;
import jpa.interfaces.WinkelmandBeanInterface;

/**
 * Servlet implementation class WinkelmandServlet
 */
@WebServlet("/WinkelmandServlet")
public class WinkelmandServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WinkelmandServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		WinkelmandBeanInterface wwagen = (WinkelmandBeanInterface) request
				.getSession().getAttribute("shoppingCar");
		InitialContext context;

		try {
			context = new InitialContext();
			ProductBeanInterface pbi = (ProductBeanInterface) context.lookup("ProductBeans");

			int id = Integer.parseInt(request.getParameter("id"));
			wwagen.voegProductInWinkelwagen(id, pbi.getProductById(id));

		} catch (Exception e) {
			// TODO: handle exception
		}

		request.setAttribute("winkelwagenProds", wwagen.getWinkelwagen());
		forwardTo("WEB-INF/winkelwagen.jsp", request, response);

	}

	private void forwardTo(String jsp, HttpServletRequest request,
			HttpServletResponse response) {
		RequestDispatcher rd = request.getRequestDispatcher(jsp);
		try {
			rd.forward(request, response);
		} catch (Exception e) {

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println(request.getParameter("Operation"));
		WinkelmandBeanInterface wwagen = (WinkelmandBeanInterface) request.getSession().getAttribute("shoppingCar");
		String bestellMessage = "";
		int bestelID = 0;
		if ((request.getParameter("Operation").equals("leeg"))) {
			wwagen.leegWinkelwagen();
		}
		else if((request.getParameter("Operation").equals("doorvoeren"))){
			
			try {
				InitialContext ctx = new InitialContext();
				ConnectionFactory cf = (ConnectionFactory) ctx.lookup("bestelFactory");
				Queue	queue = (Queue) ctx.lookup("bestelQueu");
				
				Connection con = cf.createConnection();
				Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
				MessageProducer sender = session.createProducer(queue);
				
			    Iterator it = wwagen.getWinkelwagen().entrySet().iterator();
			    while (it.hasNext()) {
			        Map.Entry pairs = (Map.Entry)it.next();
			        System.out.println(pairs.getKey() + " = " + pairs.getValue());
			        BestellingPK b = new BestellingPK();
					Product p = (Product) pairs.getKey();
			        b.setBestId(wwagen.createNewBestellingID());
			        bestelID = (int) b.getBestId();
			        String value = pairs.getValue().toString();
					b.setAantal(Long.parseLong(value));
					b.setProductId(p.getId());
					b.setKlantId(wwagen.getKlantID());
					ObjectMessage message = session.createObjectMessage(b);
					sender.send(message);
			        it.remove(); // avoids a ConcurrentModificationException
			    }

				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				bestellMessage = e.getMessage();
			}
			finally{
				
				bestellMessage = " " + bestelID + " ";
				request.setAttribute("bestellMessage", bestellMessage);
				forwardTo("WEB-INF/order.jsp", request, response);
				
			}
		//TODO aan bestelling toevoegen
		}

	}

}
